package com.example.listening;

import java.io.File;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.example.listening.bean.AnalysisBean;
import com.example.listening.bean.DanTiBean;
import com.example.listening.bean.ErrTableBean;
import com.example.listening.bean.ExamLocalBean;
import com.example.listening.bean.TaoTiBean;
import com.example.listening.examsdk.ExamSDK;
import com.example.listening.examsdk.core.Lesson;
import com.example.listening.examsdk.core.MediaItem;
import com.example.listening.examsdk.core.SubjecType;
import com.example.listening.examsdk.core.Subject;
import com.example.listening.utils.AllContacts;
import com.example.listening.utils.Logger;
import com.example.listening.utils.ObjectCacheToFile;
import com.example.listening.utils.ToolUtils;
import com.example.listening.utils.UrlUtils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 修正本
 */
public class CorrectionAnalysisActivity extends BaseActivity {

	private static final String TOSEE = "toSee";
	private static final String POSITION = "position";
	private List<ErrTableBean> errTables = new ArrayList<ErrTableBean>();
	private ExamLocalBean examLocalBean;

	private LinearLayout ll_qus_title;
	private ImageView image_result;
	private View menu_option, menu_analytical, menu_option_sure;
	private TextView topic_topic, topic_time, topic_content, topic_answer;
	private int currentPosition, total;
	private HashMap<Integer, String> names;
	private ArrayList<Integer> needRemove;

	private boolean toSee = false;
	Lesson currentLesson;
	Subject currentSubject;
	private Button btn_a,btn_b,btn_c,btn_d;
	private MediaPlayer mediaPlayer;
	private List<MediaItem> mediaItems;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_correction_analysis);

		btn_a = (Button) findViewById(R.id.button_a);
		btn_b = (Button) findViewById(R.id.button_b);
		btn_c = (Button) findViewById(R.id.button_c);
		btn_d = (Button) findViewById(R.id.button_d);
		init();
	}

	@Override
	public void initData() {
		super.initData();
		toSee = getIntent().getBooleanExtra(TOSEE, false);
		names = new HashMap<Integer, String>();
		needRemove = new ArrayList<Integer>();
		examLocalBean = (ExamLocalBean) ObjectCacheToFile.getCache(
				AllContacts.EXAMLOCALBEAN, ExamLocalBean.class, this);
		if (examLocalBean != null) {
			if(toSee){
				errTables.addAll(examLocalBean.hasDoBeans);
			}else{
				errTables.addAll(examLocalBean.errBeans);
			}
		} else {
			errTables = new ArrayList<ErrTableBean>();
		}
		if (toSee) {
			ll_qus_title.setVisibility(View.VISIBLE);
			menu_analytical.setVisibility(View.VISIBLE);
			menu_option_sure.setVisibility(View.GONE);
			findViewById(R.id.button_last_analytical).setVisibility(View.VISIBLE);
		}
		/**
		 * 头部
		 */
		total = errTables.size();
		currentPosition = getIntent().getIntExtra(POSITION, 0);
		postData();
	}

	private void postData() {
		ErrTableBean item = errTables.get(currentPosition);
		topic_time.setText((currentPosition+1) + "/" + total);
		setItemTitle(item, item.currentIndex, topic_content);
		topic_topic.setText(item.item.Body.Sub);


		if (isColzeSubject()) {
			topic_answer.setText("");
		}
		else {
			topic_answer.setText(ToolUtils.getQusContent(item.item.Body));
		}
	}


	private String daan = "";

	private void setItemTitle(ErrTableBean item, int currentIndex,
			TextView topic_content) {
		String lessonNo = item.examLesson;
		if (lessonNo != null) {
			lessonNo = lessonNo.toLowerCase().replaceAll(Lesson.ID_PERFIX.toLowerCase(),"");
		}

		//加载当前课程与题目
		currentLesson = ExamSDK.getLession(Lesson.ID_PERFIX + lessonNo);
		currentSubject = currentLesson.getSubjects().get(currentIndex - 1);

		startPlay(currentSubject.getAllMediaItem2());


		Class clazz;
		String name = "";
		String quePath = "";
		try {
			clazz = TaoTiBean.Body.class;
			Field field = clazz.getField("Q" + currentIndex);
			name = (String) field.get(item.body);
			name = name.substring(0, name.lastIndexOf("_"));
			names.put(currentPosition, name);
			BaseApplication.currentDifficulty = Integer.valueOf(name.split("_")[1]);

			if (BaseApplication.examData.get(name) == null) {
				String forwordName = AllContacts
						.getPathByType(BaseApplication.currentDifficulty)
						+ lessonNo + "/" + name;
				/**
				 * 题目内容1-5题
				 */
				quePath = forwordName + ".json";
				String content = ToolUtils.readFileByLines(quePath);
				DanTiBean danTiBean = (DanTiBean) ToolUtils.jsStrToJson(
						content, DanTiBean.class);
				BaseApplication.examData.put(name, danTiBean);

				/**
				 * 题目
				 */
				String queContentPath = forwordName + ".txt";
				if (ToolUtils.isFileExists(queContentPath)) {
					BaseApplication.examData.put(name + "_content",
							ToolUtils.readFileByLines(queContentPath));
				}
				/**
				 * 题目图片
				 */


				String queImgPath = "";
				try {
					queImgPath = currentSubject.getAllPicFile().getAbsolutePath();
				} catch (Throwable e) {

				}
				if (!TextUtils.isEmpty(queImgPath)
						&& ToolUtils.isFileExists(queImgPath)) {
					BaseApplication.examData.put(name + "_image", queImgPath);

					Logger.d("<< img file: " + queImgPath);
				}
			}
			String content = (String) BaseApplication.examData.get(name + "_content");
			if (ToolUtils.isNullOrEmpter(content)) {
				content = "";
			}

			String queImgPath = (String)BaseApplication.examData.get(name + "_image");
			Bitmap bp = null;
			if (!TextUtils.isEmpty(queImgPath)) {
				bp = ToolUtils.bytes2Bimap(ToolUtils.readFileByBytes(queImgPath));
			}
			if (bp != null) {
				ToolUtils.setImageToTextView(this, topic_content, bp, content);
			} else {
				topic_content.setText(content);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		//设置组信息
		if (isColzeSubject()) {
			//填空
			btn_a.setEnabled(false);
			btn_b.setEnabled(false);
			btn_c.setEnabled(false);
			btn_d.setEnabled(false);

			btn_a.setTextColor(Color.GRAY);
			btn_b.setTextColor(Color.GRAY);
			btn_c.setTextColor(Color.GRAY);
			btn_d.setTextColor(Color.GRAY);

			topic_answer.setEnabled(true);
			topic_answer.setSingleLine(true);
			topic_answer.setText("");
			topic_answer.setHint("请输入恰当的单词");

			topic_answer.setBackgroundDrawable(getResources().getDrawable(R.drawable.rect_border_gray));
			topic_answer.addTextChangedListener(new TextWatcher() {
				@Override
				public void beforeTextChanged(CharSequence s, int start, int count, int after) {

				}

				@Override
				public void onTextChanged(CharSequence s, int start, int before, int count) {
					daan = s.toString();

					Logger.d("<< onTextChanged: " + daan);
				}

				@Override
				public void afterTextChanged(Editable s) {

				}
			});
		} else {
			btn_a.setEnabled(true);
			btn_b.setEnabled(true);
			btn_c.setEnabled(true);
			btn_d.setEnabled(true);

			btn_a.setTextColor(getResources().getColor(R.color.text_color));
			btn_b.setTextColor(getResources().getColor(R.color.text_color));
			btn_c.setTextColor(getResources().getColor(R.color.text_color));
			btn_d.setTextColor(getResources().getColor(R.color.text_color));
			topic_answer.setHint("");

			topic_answer.setEnabled(false);
			topic_answer.setSingleLine(false);
			topic_answer.setBackgroundDrawable(null);
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		try {
			if (mediaPlayer != null && mediaPlayer.isPlaying()) {
				mediaPlayer.stop();
			}
		} catch (Throwable e) {
			e.printStackTrace();
		}
	}

	public void shutdownMediaPlayer() {
		Logger.d(">>> Shutdown MediaPlayer");
		if (mediaPlayer != null) {
			try {
				if (mediaPlayer.isPlaying()) {
					mediaPlayer.stop();
				}
				mediaPlayer.release();
			} catch (Throwable e) {

			}
			mediaPlayer = null;
		}
	}


	private void startPlay(final List<MediaItem> mediaItems) {
		if (mediaItems == null) {
			return;
		}
		shutdownMediaPlayer();
		this.mediaItems = mediaItems;

		Logger.d(">> mediaItems: " + mediaItems.toString());

		new Thread(new Runnable() {
			@Override
			public void run() {
				if (mediaItems.size() > 0) {
					MediaItem mediaItem = mediaItems.remove(0);
					playItem(mediaItem,false);
				}
			}
		}).start();
	}

	private MediaPlayer createLocalMp3(File file) {
		try {
			MediaPlayer mp = MediaPlayer.create(this, Uri.fromFile(file));
			mp.stop();
			return mp;
		} catch (Throwable e) {
			e.printStackTrace();
			Logger.d("<<createLocalMp3 Throwable: " + file);
		}
		return null;
	}

	private void playItem(final MediaItem mediaItem,final boolean playReplayMp3) {
		if (mediaItem == null) {
			return;
		}

		File mp3File  = null;
		if (playReplayMp3) {
			mp3File = currentLesson.getReplayMp3File();
			Logger.d(">> mediaitem play REPLAY.MP3: " + mp3File.toString().toUpperCase());
		} else {
			mp3File = mediaItem.getMp3File();
			Logger.d(">> mediaItem play: " + mediaItem.toString());
		}

//		if (true) {
//			if (playReplayMp3) {
//				playItem(mediaItem, false);
//			} else {
//				if (mediaItem.getReplay() != 0) {
//					mediaItem.setReplay(mediaItem.getReplay() - 1);
//					playItem(mediaItem,true);
//				} else {
//					handler.postDelayed(new Runnable() {
//						@Override
//						public void run() {
//							if (mediaItems.size() > 0) {
//								MediaItem mediaItem = mediaItems.remove(0);
//								playItem(mediaItem,false);
//							} else {
//								Logger.d(">> 播放结束了");
//							}
//						}
//					}, mediaItem.getDelaySecond() * 1000);
//					Logger.d("<< mediaItem 延迟: " + mediaItem.getDelaySecond() + "秒");
//				}
//			}
//			return;
//		}
		try {
			mediaPlayer = createLocalMp3(mp3File);
			if (mediaPlayer == null) {
				if (playReplayMp3) {
					playItem(mediaItem, false);
				} else {
					if (mediaItem.getReplay() > 0) {
						mediaItem.setReplay(mediaItem.getReplay() - 1);
						playItem(mediaItem,true);
					} else {
						handler.postDelayed(new Runnable() {
							@Override
							public void run() {
								if (mediaItems != null && mediaItems.size() > 0) {
									MediaItem mediaItem = mediaItems.remove(0);
									playItem(mediaItem,false);
								} else {
									Logger.d(">> 播放结束了");
									shutdownMediaPlayer();
								}
							}
						}, mediaItem.getDelaySecond() * 1000);
						Logger.d("<< mediaItem 延迟: " + mediaItem.getDelaySecond() + "秒");
					}
				}
				return;
			}
			//当播放完音频资源时，会触发onCompletion事件，可以在该事件中释放音频资源，
			//以便其他应用程序可以使用该资源:
			mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
				@Override
				public void onCompletion(MediaPlayer mp) {
					mp.release();//释放音频资源
					if (playReplayMp3) {
						playItem(mediaItem, false);
					} else {
						if (mediaItem.getReplay() > 0) {
							mediaItem.setReplay(mediaItem.getReplay() - 1);
							playItem(mediaItem,true);
						} else {
							handler.postDelayed(new Runnable() {
								@Override
								public void run() {
									if (mediaItems.size() > 0) {
										MediaItem mediaItem = mediaItems.remove(0);
										playItem(mediaItem,false);
									} else {
										Logger.d(">> 播放结束了");
										shutdownMediaPlayer();
									}
								}
							}, mediaItem.getDelaySecond() * 1000);
							Logger.d("<< mediaItem 延迟: " + mediaItem.getDelaySecond() + "秒");
						}
					}
				}
			});
			//在播放音频资源之前，必须调用Prepare方法完成些准备工作
			mediaPlayer.prepare();
			//开始播放音频
			mediaPlayer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//是否是填空题
	public boolean isColzeSubject() {
		try {
			if (currentSubject != null && currentSubject.getType() == SubjecType.colze) {
				return true;
			}
		} catch (Throwable e) {
			//e.printStackTrace();
		}
		return false;
	}

	@Override
	public void initWidget() {
		super.initWidget();
		ll_qus_title = (LinearLayout) findViewById(R.id.ll_qus_title);
		image_result = (ImageView) findViewById(R.id.image_result);
		topic_topic = (TextView) findViewById(R.id.topic_topic);
		topic_time = (TextView) findViewById(R.id.topic_time);
		topic_content = (TextView) findViewById(R.id.topic_content);
		topic_answer = (TextView) findViewById(R.id.topic_answer);
		menu_option_sure = findViewById(R.id.menu_option_sure);
		menu_analytical = findViewById(R.id.menu_analytical);
		menu_option = findViewById(R.id.menu_option);
		findViewById(R.id.button_last_analytical).setVisibility(View.GONE);
	}

	private String userAns = "";
	
	private void setButton(int type) {
		switch (type) {
			case 0:
				((Button) findViewById(R.id.button_aa))
						.setBackgroundResource(R.drawable.button_selector_default);
				((Button) findViewById(R.id.button_aa)).setTextColor(getResources()
						.getColor(R.color.select_item_default));
				((Button) findViewById(R.id.button_bb))
						.setBackgroundResource(R.drawable.button_selector_default);
				((Button) findViewById(R.id.button_bb)).setTextColor(getResources()
						.getColor(R.color.select_item_default));
				((Button) findViewById(R.id.button_cc))
						.setBackgroundResource(R.drawable.button_selector_default);
				((Button) findViewById(R.id.button_cc)).setTextColor(getResources()
						.getColor(R.color.select_item_default));
				((Button) findViewById(R.id.button_dd))
						.setBackgroundResource(R.drawable.button_selector_default);
				((Button) findViewById(R.id.button_dd)).setTextColor(getResources()
						.getColor(R.color.select_item_default));
				break;
			case 1:
				((Button) findViewById(R.id.button_aa))
						.setBackgroundResource(R.drawable.xuanti_button_click);
				((Button) findViewById(R.id.button_aa)).setTextColor(getResources()
						.getColor(R.color.white));
				((Button) findViewById(R.id.button_bb))
						.setBackgroundResource(R.drawable.button_selector_default);
				((Button) findViewById(R.id.button_bb)).setTextColor(getResources()
						.getColor(R.color.select_item_default));
				((Button) findViewById(R.id.button_cc))
						.setBackgroundResource(R.drawable.button_selector_default);
				((Button) findViewById(R.id.button_cc)).setTextColor(getResources()
						.getColor(R.color.select_item_default));
				((Button) findViewById(R.id.button_dd))
						.setBackgroundResource(R.drawable.button_selector_default);
				((Button) findViewById(R.id.button_dd)).setTextColor(getResources()
						.getColor(R.color.select_item_default));
				break;
			case 2:
				((Button) findViewById(R.id.button_aa))
						.setBackgroundResource(R.drawable.button_selector_default);
				((Button) findViewById(R.id.button_aa)).setTextColor(getResources()
						.getColor(R.color.select_item_default));
				((Button) findViewById(R.id.button_bb))
						.setBackgroundResource(R.drawable.xuanti_button_click);
				((Button) findViewById(R.id.button_bb)).setTextColor(getResources()
						.getColor(R.color.white));
				((Button) findViewById(R.id.button_cc))
						.setBackgroundResource(R.drawable.button_selector_default);
				((Button) findViewById(R.id.button_cc)).setTextColor(getResources()
						.getColor(R.color.select_item_default));
				((Button) findViewById(R.id.button_dd))
						.setBackgroundResource(R.drawable.button_selector_default);
				((Button) findViewById(R.id.button_dd)).setTextColor(getResources()
						.getColor(R.color.select_item_default));
				break;
			case 3:
				((Button) findViewById(R.id.button_aa))
						.setBackgroundResource(R.drawable.button_selector_default);
				((Button) findViewById(R.id.button_aa)).setTextColor(getResources()
						.getColor(R.color.select_item_default));
				((Button) findViewById(R.id.button_bb))
						.setBackgroundResource(R.drawable.button_selector_default);
				((Button) findViewById(R.id.button_bb)).setTextColor(getResources()
						.getColor(R.color.select_item_default));
				((Button) findViewById(R.id.button_cc))
						.setBackgroundResource(R.drawable.xuanti_button_click);
				((Button) findViewById(R.id.button_cc)).setTextColor(getResources()
						.getColor(R.color.white));
				((Button) findViewById(R.id.button_dd))
						.setBackgroundResource(R.drawable.button_selector_default);
				((Button) findViewById(R.id.button_dd)).setTextColor(getResources()
						.getColor(R.color.select_item_default));
				break;
			case 4:
				((Button) findViewById(R.id.button_aa))
						.setBackgroundResource(R.drawable.button_selector_default);
				((Button) findViewById(R.id.button_aa)).setTextColor(getResources()
						.getColor(R.color.select_item_default));
				((Button) findViewById(R.id.button_bb))
						.setBackgroundResource(R.drawable.button_selector_default);
				((Button) findViewById(R.id.button_bb)).setTextColor(getResources()
						.getColor(R.color.select_item_default));
				((Button) findViewById(R.id.button_cc))
						.setBackgroundResource(R.drawable.button_selector_default);
				((Button) findViewById(R.id.button_cc)).setTextColor(getResources()
						.getColor(R.color.select_item_default));
				((Button) findViewById(R.id.button_dd))
						.setBackgroundResource(R.drawable.xuanti_button_click);
				((Button) findViewById(R.id.button_dd)).setTextColor(getResources()
						.getColor(R.color.white));
				break;
			default:
				break;
		}
	}
	@Override
	public void onViewClick(View v) {
		super.onViewClick(v);
		switch (v.getId()) {
		case R.id.ib_back:
			finish();
			break;
		case R.id.button_aa:
			setButton(1);
			userAns = "A";
			break;
		case R.id.button_bb:
			setButton(2);
			userAns = "B";
			break;
		case R.id.button_cc:
			setButton(3);
			userAns = "C";
			break;
		case R.id.button_dd:
			setButton(4);
			userAns = "D";
			break;
		case R.id.button_translation:
			topic_answer.setText(getBean().item.Key.Content + "");
			//topic_answer.setText(BaseApplication.examData.get(names.get(currentPosition) + "_CH").toString());
			break;
		case R.id.button_vocabulary:
			//播放声音
			if (currentSubject != null) {
				startPlay(currentSubject.getAllMediaItem2());
			}

			//topic_answer.setText(getBean().item.Key.Word);
			//topic_answer.setText(BaseApplication.examData.get(names.get(currentPosition) + "_WD").toString());
			break;
		case R.id.button_detailed:
			topic_answer.setText(getBean().item.Key.Point + "");
			break;
		case R.id.button_skill:
			topic_answer.setText(getBean().item.Key.Skill + "");
			break;
		case R.id.button_analysis:
			String txt = "";
			if (!ToolUtils.isNullOrEmpter(getBean().head.Txt)) {
				txt = getBean().head.Txt.replaceAll(".txt", "");
			}
			if (!ToolUtils.isNullOrEmpter(getBean().head.Pic)) {
				txt = getBean().head.Pic.replaceAll(".png", "");
			}
			txt += "_Q" + getBean().currentIndex;
			getDataByGet(
					UrlUtils.getUrl(UrlUtils.MethodName.GETANALYSIS,
							new String[] {
									BaseApplication.loginBean.data.userName,
									txt }),
					UrlUtils.MethodType.TYPE_GETANALYSIS, handler);
			break;
		case R.id.button_last_analytical:
			if (currentPosition > 0) {
				currentPosition--;
			} else {
				showToast("这是第一题");
				return;
			}
			postData();
			break;
		case R.id.button_next_analytical:
			currentPosition++;
			if (currentPosition >= total) {
				showToast("这是最后一题");
				currentPosition--;
				return;
			}
			if (!toSee) {
				resumeView();
			}
			postData();
			break;
		case R.id.button_sure:
			setButton(0);
			checkAns(userAns);
			break;

		default:
			break;
		}
	}

	private void resumeView() {
		ll_qus_title.setVisibility(View.GONE);
		menu_analytical.setVisibility(View.GONE);
		menu_option_sure.setVisibility(View.VISIBLE);
	}

	private void checkAns(String useAns) {
		topic_answer.setHint("");
		topic_answer.setEnabled(false);
		topic_answer.setSingleLine(false);
		topic_answer.setBackgroundDrawable(null);

		ll_qus_title.setVisibility(View.VISIBLE);
		menu_analytical.setVisibility(View.VISIBLE);
		menu_option.setVisibility(View.GONE);
		menu_option_sure.setVisibility(View.GONE);
		topic_answer.setText(ToolUtils.getQusAns(getBean().item.Key));
		if (useAns.equals(getBean().item.Key.Ans)) {
			image_result.setImageResource(R.drawable.right);
			needRemove.add(currentPosition);
		} else {
			image_result.setImageResource(R.drawable.wrong);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (examLocalBean != null) {
			for (Integer i : needRemove) {
				if (examLocalBean.hasDoBeans == null) {
					examLocalBean.hasDoBeans = new ArrayList<ErrTableBean>();
				}
				examLocalBean.hasDoBeans.add(examLocalBean.errBeans.get(i));
			}
			for (Integer i : needRemove) {
				examLocalBean.errBeans.remove(errTables.get(i));
			}
		}
		ObjectCacheToFile.doCache(AllContacts.EXAMLOCALBEAN, examLocalBean,
				this);
	}

	private ErrTableBean getBean() {
		return errTables.get(currentPosition);
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case UrlUtils.MethodType.TYPE_GETANALYSIS:
			if (msg.obj != null) {
				AnalysisBean response = (AnalysisBean) msg.obj;
				if (response.status == 1) {
					if (response.data.qu_allCount > 0) {
						int all = response.data.qu_allCount;
						int a = response.data.qu_A_count;
						int b = response.data.qu_B_count;
						int c = response.data.qu_C_count;
						int d = response.data.qu_D_count;
						String content = "选择A的人数占: "
								+ ToolUtils.getStringByFloat(Float
										.valueOf((float) a / all)) + "\n";
						content += "选择B的人数占: "
								+ ToolUtils.getStringByFloat(Float
										.valueOf((float) b / all)) + "\n";
						content += "选择C的人数占: "
								+ ToolUtils.getStringByFloat(Float
										.valueOf((float) c / all)) + "\n";
						content += "选择D的人数占: "
								+ ToolUtils.getStringByFloat(Float
										.valueOf((float) d / all)) + "";
						showToast(content);
					} else {
						showToast("暂无数据");
					}
				} else {
					showToast(response.msg + "");
				}
			}
			break;

		default:
			break;
		}
		return super.handleMessage(msg);
	}

	public static Intent createIntent(Context context, boolean toSee, int position) {
		Intent intent = new Intent(context, CorrectionAnalysisActivity.class);
		intent.putExtra(TOSEE, toSee);
		intent.putExtra(POSITION, position);
		return intent;
	}
}
